package com.jbit.examSystem.controller;

import com.google.code.kaptcha.Constants;
import com.jbit.examSystem.exception.LoginErrorException;
import com.jbit.examSystem.exception.RegisterException;
import com.jbit.examSystem.pojo.Administrator;
import com.jbit.examSystem.pojo.Student;
import com.jbit.examSystem.pojo.Teacher;
import com.jbit.examSystem.pojo.User;
import com.jbit.examSystem.service.AdminService;
import com.jbit.examSystem.service.StudentService;
import com.jbit.examSystem.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import com.jbit.examSystem.dto.UserDto;
import com.jbit.examSystem.vo.UserVo;
import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginAndRegisterController {
    @Autowired
    private StudentService studentService;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private AdminService adminService;

    @RequestMapping("register")
    public String register(UserVo userVo, Model model, HttpSession session){
        UserDto userDto = new UserDto();
        try {
            PropertyUtils.copyProperties(userDto, userVo);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //学员注册
        if (userVo.getIdentityId()==10000){
            try {
                studentService.register(userDto);
            } catch (RegisterException e) {
                e.printStackTrace();
                model.addAttribute("registerErrorMsg", e.getMessage());
                return "register";
            }
            //教员注册
        }else if (userVo.getIdentityId()==10001){
            teacherService.register(userDto);
        }
        session.removeAttribute("emailCode");
        model.addAttribute("user", userVo);
        return "login";
    }

    @RequestMapping("login")
    public String login(UserVo userVo,Boolean rememberMe, HttpSession session,HttpServletResponse resp,
                        HttpServletRequest req){
        UserDto userDto = new UserDto();
        Date loginTime = new Date();


        try {
            PropertyUtils.copyProperties(userDto,userVo);

            if (userVo.getIdentityId() == 10000){
                Student student = studentService.login(userDto);
                Date lastLoginTime = student.getLoginTime();
                studentService.setLoginTime(loginTime,student.getId(),lastLoginTime);
                session.setAttribute("user",student);
            }
            else if (userVo.getIdentityId() == 10001){
                Teacher teacher = teacherService.login(userDto);
                Date lastLoginTime = teacher.getLoginTime();
                teacherService.setLoginTime(loginTime,teacher.getId(),lastLoginTime);
                session.setAttribute("user",teacher);
            }
            else if (userVo.getIdentityId() == 10002){
                Administrator admin = adminService.login(userDto);
                Date lastLoginTime = admin.getLoginTime();
                adminService.setLoginTime(loginTime,admin.getId(),lastLoginTime);
                session.setAttribute("user",admin);
            }

            Cookie[] cookies = {
                    new Cookie("username", URLEncoder.encode(userVo.getName(), "UTF-8")),
                    new Cookie("password", URLEncoder.encode(userVo.getPassword(), "UTF-8")),
                    new Cookie("identityId", URLEncoder.encode(userVo.getIdentityId().toString(), "UTF-8"))
            };

            for (Cookie cookie : cookies) {
                cookie.setMaxAge(7*24*60*60);
                if (rememberMe == null) {
                    cookie.setMaxAge(0);
                }
                resp.addCookie(cookie);
            }

            return "redirect:index";
        } catch (LoginErrorException e){
            req.setAttribute("errorMsg", e.getMessage());
            return "login";
        } catch (Exception e) {
            e.printStackTrace();
            return "login";
        }
    }

    @RequestMapping("logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");

        return "login";
    }

    @RequestMapping("checkCode")
    @ResponseBody
    public Map<String,Object> checkCode(String code ,HttpSession session){
        String token = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        boolean exists = code.equalsIgnoreCase(token);
        Map<String, Object> map = new HashMap<>();
        map.put("valid",exists);

        return map;
    }
}
